//将parent环境set到自己的环境中
window.electron = window.top.electron
window.$ = (args) => window.top.$(args, document);
document.notification = window.top.document.notification
document.print = window.top.document.print
document.println = window.top.document.println
document.printclear = window.top.document.printclear
window.GetDocuemtnChildNodes = window.top.GetDocuemtnChildNodes
window.GetUUID = window.top.GetUUID
document.Page = window.top.document.Page

const { sqlite, databases } = electron.JDBC();

let likeChangeIntv = -1;
let likeChangeDelay = 800;

const likeChange = (value) => {
    if (!value || value == "") {
        return;
    }
    document.querySelector("#typeInput").value = "";

    clearTimeout(likeChangeIntv);
    likeChangeIntv = setTimeout(() => {
        clearResult();
        sqlite.enums.queryByText(value).then(result => {

            if (!result || result.length <= 0) {
                return;
            }

            insertResult(result, value)
        })
    }, likeChangeDelay)
}

const typeChange = (value) => {
    if (!value || value == "") {
        return;
    }

    document.querySelector("#likeInput").value = "";

    clearResult();
    sqlite.enums.queryByTypeZh(value).then(result => {
        if (!result || result.length <= 0) {
            return;
        }

        insertResult(result)
    })
}

const resultRowDelete = (e) => {

}

const marskShow = (flag) => {
    if (flag) {
        marsk.className = marsk.className.replaceAll("hidden", "").trim();//打开遮罩层
    } else {
        marsk.className += " hidden";
    }
}

const resultRowChange = (e) => {
    document.querySelector("#typeInput").value = "";

    //校验非空字段
    const inputname = $(e).attr("name");

    if (inputname == "name" && e.value == "") {
        $(e).addClass("wrong")
        return;

    } else if (inputname == "nameZh" && e.value == "") {
        $(e).addClass("wrong")
        return;

    } else if (inputname == "type" && e.value == "") {
        $(e).addClass("wrong")
        return;

    } else if (inputname == "typeZh" && e.value == "") {
        $(e).addClass("wrong")
        return;

    } else if (inputname == "solt" && e.value == "") {
        $(e).addClass("wrong")
        return;

    } else {
        $(e).removeClass("wrong") //校验通过
    }

    const tr = $(e).parent().parent()

    const newData = {
        id: tr.data("id"),
        name: tr.find('input[name=name]').val(),
        name_zh: tr.find('input[name=nameZh]').val(),
        type: tr.find('input[name=type]').val(),
        type_zh: tr.find('input[name=typeZh]').val(),
        solt: tr.find('input[name=solt]').val(),
        remark: tr.find('input[name=remark]').val(),
    }

    //校验其他单元格非空字段
    if (newData.name == "") {
        return;
    }

    if (newData.name_zh == "") {
        return;
    }

    if (newData.type == "") {
        return;
    }

    if (newData.type_zh == "") {
        return;
    }

    if (newData.solt == "") {
        return;
    } else {
        newData.solt = parseInt(newData.solt); //需要转成int
    }

    if (newData.id == "") {
        return
    } else {
        newData.id = parseInt(newData.id); //需要转成int
    }

    console.log("resultRowChange", e.value, newData);
    sqlite.enums.update(newData).then(result => {
        console.log("更新了一条记录")
    });

}

const addResultRowChange = (e) => {

    //校验非空字段
    const inputname = $(e).attr("name");

    if (inputname == "name" && e.value == "") {
        $(e).addClass("wrong")
        return;

    } else if (inputname == "nameZh" && e.value == "") {
        $(e).addClass("wrong")
        return;

    } else if (inputname == "type" && e.value == "") {
        $(e).addClass("wrong")
        return;

    } else if (inputname == "typeZh" && e.value == "") {
        $(e).addClass("wrong")
        return;

    } else if (inputname == "solt" && e.value == "") {
        $(e).addClass("wrong")
        return;

    } else {
        $(e).removeClass("wrong") //校验通过
    }

    const tr = $(e).parent().parent()

    const newData = {
        id: tr.data("id"),
        name: tr.find('input[name=name]').val(),
        name_zh: tr.find('input[name=nameZh]').val(),
        type: tr.find('input[name=type]').val(),
        type_zh: tr.find('input[name=typeZh]').val(),
        solt: tr.find('input[name=solt]').val(),
        remark: tr.find('input[name=remark]').val(),
    }

    //校验其他单元格非空字段
    if (newData.name == "") {
        return;
    }

    if (newData.name_zh == "") {
        return;
    }

    if (newData.type == "") {
        return;
    }

    if (newData.type_zh == "") {
        return;
    }

    if (newData.solt == "") {
        return;
    } else {
        newData.solt = parseInt(newData.solt); //需要转成int
    }

    if (newData.id == "") {
        return
    } else {
        newData.id = parseInt(newData.id); //需要转成int
    }

    console.log("addResultRowChange", e.value, newData);
}

const addResultRowDelete = (e) => {

}

//插入查询结果
const insertResult = (datas, keyword) => {
    keyword = keyword || 'knciik@qq.com' //设定一个不常用单词，在keyword为空时防止加class

    let inner = "";
    datas.forEach(data => {
        inner += `<tr data-id="${data.id}">`
        inner += `<td><input name="type"   class="${data.type.indexOf(keyword) == -1 ? "" : "keyword"}"    onchange="resultRowChange(this)" value="${data.type}"    ${currentModifyEnable ? "" : "readOnly='true'"} ></td>`
        inner += `<td><input name="typeZh" class="${data.type_zh.indexOf(keyword) == -1 ? "" : "keyword"}" onchange="resultRowChange(this)" value="${data.type_zh}" ${currentModifyEnable ? "" : "readOnly='true'"} ></td>`
        inner += `<td><input name="name"   class="${data.name.indexOf(keyword) == -1 ? "" : "keyword"}"    onchange="resultRowChange(this)" value="${data.name}"    ${currentModifyEnable ? "" : "readOnly='true'"} ></td>`
        inner += `<td><input name="nameZh" class="${data.name_zh.indexOf(keyword) == -1 ? "" : "keyword"}" onchange="resultRowChange(this)" value="${data.name_zh}" ${currentModifyEnable ? "" : "readOnly='true'"} ></td>`
        inner += `<td><input name="solt"   type="number"                                                   onchange="resultRowChange(this)" value="${data.solt}"    ${currentModifyEnable ? "" : "readOnly='true'"} ></td>`
        inner += `<td><input name="remark" class="${data.remark.indexOf(keyword) == -1 ? "" : "keyword"}"  onchange="resultRowChange(this)" value="${data.remark}"  ${currentModifyEnable ? "" : "readOnly='true'"} ></td>`

        inner += `<td>
            <button class="hover-show hidden color-red" onclick="resultRowDelete(this)">删除</button>
        </td>`
        inner += '</tr>'
    })

    document.querySelector("#tbody").innerHTML = inner;
}

//插入新增行
const addResult = () => {
    const tr = $(`
        <tr data-id="">
            <td><input name="type"   class="wrong" onchange="addResultRowChange(this)" value=""> </td>
            <td><input name="typeZh" class="wrong" onchange="addResultRowChange(this)" value=""></td>
            <td><input name="name"   class="wrong" onchange="addResultRowChange(this)" value=""></td>
            <td><input name="nameZh" class="wrong" onchange="addResultRowChange(this)" value=""></td>
            <td><input name="solt"   class="wrong" onchange="addResultRowChange(this)" value="" type="number"></td>
            <td><input name="remark" class="wrong" onchange="addResultRowChange(this)" value=""></td>
            <td><button onclicl="">取消</td>
        </tr>
    `)

    $("#tbody").append(tr);
}

const clearResult = () => {
    document.querySelector("#tbody").innerHTML = "";
}

const reflashPage = () => {
    window.location.reload();
}

let currentModifyEnable = false; //是否可修改  //默认不可修改

const lockModify = (e) => {
    console.log("lockModify", e, currentModifyEnable)
    if (currentModifyEnable) {
        //加锁
        currentModifyEnable = false;
        e.querySelector(".icon-lock").style.display = "inline-block";
        e.querySelector(".icon-unlock").style.display = "none";
        document.println("已锁定,不可修改内容")

        //页面input改成readOnly
        $("#tbody").find("input").each((i, input) => {
            input.readOnly = true
        })
    } else {
        //解锁
        currentModifyEnable = true;
        e.querySelector(".icon-lock").style.display = "none";
        e.querySelector(".icon-unlock").style.display = "inline-block";
        document.println("已解除锁定,可以修改内容")

        //页面input取消readOnly
        $("#tbody").find("input").each((i, input) => {
            input.readOnly = false
        })
    }
}

const init = () => {
    //查询type字段 写入select中
    sqlite.enums.queryAllTypes()
        .then(result => {

            if (!result || result.length <= 0) {
                return
            }

            let inner = `<option value="">-----</option>`
            result.forEach(r => {
                inner += `<option value="${r['type_zh']}">${r['type_zh']}</option>`
            })

            const typeInput = document.querySelector("#typeInput")
            typeInput.innerHTML = inner;
            typeInput.value = "";

            //第一次打开时 随机加载一个type  防止页面太空
            const index = Math.floor(Math.random() * result.length);
            typeChange(result[index].type_zh);

        })
        .catch(err => {
            console.error(err)
            document.println(err.toString())
        })
}

const resetSqlDefault = (e) => {
    e.disabled = true;
    marskShow(true);

    electron.openConfirmDialog("确定要重置吗？这将导致删除一切更改,恢复到程序原始值", ["别啰嗦快点的", "还是算了"], "warning").then(result => {
        // console.log("result", result);
        if (result.checkboxChecked || result.response == 1) {
            console.log("取消重置")
            marskShow(false);
            e.disabled = false;
            return;
        } else if (result.response == 0) {
            console.log("开始重置")
            document.println("正在重置请稍等...")
            clearResult();

            //重置 @TODO @TEST
            setTimeout(() => {
                document.println("重置失败")
                marskShow(false);
                e.disabled = false;
            }, 2000)
        }
    })
}

window.onload = function () {
     //全局字体颜色
     {
        const topBody = window.top.document.querySelector("body")
        const body = document.querySelector("body")

        if (topBody.style.color) {
            body.style.color = topBody.style.color
        }
    }
    
    init();
}